import os
import django
import random
from datetime import datetime, timedelta
from django.utils import timezone

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

# 导入模型
from projects.models import Project, Version
from cases.models import TestCase
from ai_integration.models import AITemplate, RequirementAnalysis, AIGenerationLog, GeneratedTestCaseMapping

# 随机生成日期的函数
def random_date(start, end):
    # 确保两个datetime对象都有时区信息
    if timezone.is_naive(start):
        start = timezone.make_aware(start)
    if timezone.is_naive(end):
        end = timezone.make_aware(end)
    
    # 确保start在end之前，如果不是则交换
    if start > end:
        start, end = end, start
    
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    
    # 确保有足够的时间差，如果没有则增加1天
    if int_delta <= 0:
        end = end + timedelta(days=1)
        delta = end - start
        int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    
    random_second = random.randrange(int_delta)
    return start + timedelta(seconds=random_second)

# 创建示例项目
def create_projects():
    print("正在创建示例项目...")
    
    projects_data = [
        {
            "name": "电商平台系统",
            "description": "一个完整的电商平台，包含商品管理、订单管理、用户管理等功能。"
        },
        {
            "name": "客户关系管理系统",
            "description": "用于管理客户信息、销售线索、客户互动等的CRM系统。"
        },
        {
            "name": "企业资源规划系统",
            "description": "集成了财务、人力资源、供应链等模块的ERP系统。"
        }
    ]
    
    projects = []
    for data in projects_data:
        project = Project.objects.create(
            name=data["name"],
            description=data["description"],
            created_at=random_date(timezone.now() - timedelta(days=180), timezone.now())
        )
        projects.append(project)
    
    return projects

# 为项目创建版本
def create_versions(projects):
    print("正在创建示例版本...")
    
    versions = []
    version_patterns = ["1.0.0", "1.1.0", "2.0.0", "2.1.0"]
    
    for project in projects:
        # 为每个项目创建2-3个版本
        num_versions = random.randint(2, 3)
        for i in range(num_versions):
            version = Version.objects.create(
                project=project,
                version_number=version_patterns[i % len(version_patterns)],
                description=f"{project.name} {version_patterns[i % len(version_patterns)]}版本",
                created_at=random_date(project.created_at, timezone.now())
            )
            versions.append(version)
    
    return versions

# 创建示例测试用例
def create_test_cases(versions):
    print("正在创建示例测试用例...")
    
    priorities = ["high", "medium", "low"]
    statuses = ["draft", "reviewing", "approved", "rejected", "passed", "failed"]
    test_methods = ["functional", "performance", "security", "usability", "compatibility", "other"]
    
    test_cases = []
    
    # 电商平台的测试用例模板
    ecommerce_case_templates = [
        {
            "title": "用户注册功能测试",
            "description": "验证用户是否能够成功注册新账号",
            "precondition": "用户未注册",
            "steps": "1. 访问注册页面\n2. 填写注册信息\n3. 点击注册按钮",
            "expected_result": "用户注册成功并自动登录",
            "module": "用户管理"
        },
        {
            "title": "商品搜索功能测试",
            "description": "验证用户是否能够准确搜索到商品",
            "precondition": "系统中有商品数据",
            "steps": "1. 在搜索框输入关键词\n2. 点击搜索按钮",
            "expected_result": "显示与关键词相关的商品列表",
            "module": "商品管理"
        },
        {
            "title": "购物车功能测试",
            "description": "验证用户是否能够将商品加入购物车",
            "precondition": "用户已登录",
            "steps": "1. 浏览商品\n2. 选择商品加入购物车",
            "expected_result": "商品成功加入购物车",
            "module": "订单管理"
        }
    ]
    
    # CRM系统的测试用例模板
    crm_case_templates = [
        {
            "title": "客户信息添加测试",
            "description": "验证是否能够成功添加新客户信息",
            "precondition": "用户有添加客户权限",
            "steps": "1. 进入客户管理页面\n2. 点击添加按钮\n3. 填写客户信息",
            "expected_result": "客户信息添加成功",
            "module": "客户管理"
        },
        {
            "title": "销售线索转换测试",
            "description": "验证是否能够将销售线索转换为客户",
            "precondition": "有销售线索数据",
            "steps": "1. 选择销售线索\n2. 点击转换按钮",
            "expected_result": "销售线索成功转换为客户",
            "module": "销售管理"
        }
    ]
    
    # ERP系统的测试用例模板
    erp_case_templates = [
        {
            "title": "采购订单创建测试",
            "description": "验证是否能够成功创建采购订单",
            "precondition": "有供应商信息",
            "steps": "1. 进入采购管理\n2. 创建采购订单\n3. 提交审核",
            "expected_result": "采购订单创建成功并进入审核流程",
            "module": "采购管理"
        },
        {
            "title": "库存盘点功能测试",
            "description": "验证库存盘点功能是否正常工作",
            "precondition": "有库存数据",
            "steps": "1. 进入库存管理\n2. 选择盘点功能\n3. 录入盘点数量",
            "expected_result": "盘点数据保存成功，库存数量更新",
            "module": "库存管理"
        }
    ]
    
    # 为每个版本创建测试用例
    for version in versions:
        project_name = version.project.name
        
        # 根据项目类型选择对应的测试用例模板
        if "电商" in project_name:
            case_templates = ecommerce_case_templates
        elif "客户" in project_name:
            case_templates = crm_case_templates
        else:
            case_templates = erp_case_templates
        
        # 为每个版本创建3-5个测试用例
        num_cases = random.randint(3, 5)
        for i in range(num_cases):
            # 随机选择或创建测试用例
            if i < len(case_templates):
                template = case_templates[i]
            else:
                template = {
                    "title": f"测试用例{i+1}",
                    "description": f"这是一个测试用例{i+1}",
                    "precondition": "前置条件",
                    "steps": "测试步骤",
                    "expected_result": "预期结果",
                    "module": "未分类"
                }
            
            # 生成唯一的用例ID
            case_id = f"{version.project.name.replace(' ', '_')}_{version.version_number}_{i + 1:03d}"
            while TestCase.objects.filter(case_id=case_id).exists():
                i += 1
                case_id = f"{version.project.name.replace(' ', '_')}_{version.version_number}_{i + 1:03d}"
            
            test_case = TestCase.objects.create(
                version=version,
                case_id=case_id,
                title=template["title"],
                description=template["description"],
                precondition=template["precondition"],
                steps=template["steps"],
                expected_result=template["expected_result"],
                priority=random.choice(priorities),
                status=random.choice(statuses),
                test_method=random.choice(test_methods),
                module=template["module"],
                created_by="系统管理员",
                created_at=random_date(version.created_at, timezone.now()),
                is_automated=random.choice([True, False])
            )
            
            test_cases.append(test_case)
    
    return test_cases

# 创建AI模板
def create_ai_templates():
    print("正在创建AI模板...")
    
    templates = [
        {
            "name": "基础测试用例生成模板",
            "project_type": "general",
            "content": "根据以下需求生成测试用例：{requirement}\n\n测试用例应包含：标题、描述、前置条件、测试步骤、预期结果、优先级、模块。",
            "is_default": True
        },
        {
            "name": "安全测试模板",
            "project_type": "security",
            "content": "分析以下系统或功能的安全风险，并生成对应的安全测试用例：{system_description}",
            "is_default": False
        },
        {
            "name": "性能测试模板",
            "project_type": "performance",
            "content": "为以下功能设计性能测试用例，重点关注并发处理能力：{feature_description}",
            "is_default": False
        }
    ]
    
    created_templates = []
    for template_data in templates:
        template = AITemplate.objects.create(
            name=template_data["name"],
            project_type=template_data["project_type"],
            content=template_data["content"],
            is_default=template_data["is_default"],
            created_at=random_date(timezone.now() - timedelta(days=90), timezone.now())
        )
        created_templates.append(template)
    
    return created_templates

# 创建需求分析记录
def create_requirement_analyses(projects):
    print("正在创建需求分析记录...")
    
    analyses = []
    
    analysis_templates = [
        {
            "requirement_text": "实现用户注册功能，包括邮箱验证和密码重置",
            "analysis_result": "需要创建用户表、验证逻辑、邮件发送服务、密码重置流程"
        },
        {
            "requirement_text": "开发商品搜索功能，支持关键词搜索和筛选",
            "analysis_result": "需要设计搜索算法、筛选条件、搜索结果展示页面"
        },
        {
            "requirement_text": "设计购物车功能，支持添加、删除、修改商品数量",
            "analysis_result": "需要创建购物车表、商品数量计算逻辑、价格更新机制"
        }
    ]
    
    # 为部分项目创建需求分析记录
    for project in projects[:2]:  # 只为前两个项目创建
        for template in analysis_templates:
            analysis = RequirementAnalysis.objects.create(
                project=project,
                original_content=template["requirement_text"],
                analysis_result=template["analysis_result"],
                analyzed_by="系统管理员"
            )
            analyses.append(analysis)
    
    return analyses

# 创建AI生成日志
def create_ai_generation_logs(projects, versions, test_cases):
    print("正在创建AI生成日志...")
    
    logs = []
    
    # 获取默认的AI模板
    default_template = AITemplate.objects.filter(is_default=True).first()
    
    # 为部分版本创建生成日志
    for version in versions[:3]:  # 只为前3个版本创建
        # 随机选择该版本下的一些测试用例作为AI生成的
        version_cases = [case for case in test_cases if case.version == version]
        if version_cases:
            # 随机选择1-3个测试用例作为本次生成的
            num_generated = random.randint(1, min(3, len(version_cases)))
            generated_cases = random.sample(version_cases, num_generated)
            
            log = AIGenerationLog.objects.create(
                project=version.project,
                version=version,
                prompt="生成该版本的测试用例",
                generated_cases=num_generated,
                is_success=True,
                created_by="系统管理员"
            )
            logs.append(log)
            
            # 创建生成用例映射
            for case in generated_cases:
                GeneratedTestCaseMapping.objects.create(
                    generation_log=log,
                    test_case=case
                )
    
    return logs

# 主函数
def main():
    print("开始填充示例数据...")
    
    # 创建项目
    projects = create_projects()
    
    # 创建版本
    versions = create_versions(projects)
    
    # 创建测试用例
    test_cases = create_test_cases(versions)
    
    # 创建AI模板
    ai_templates = create_ai_templates()
    
    # 创建需求分析
    requirement_analyses = create_requirement_analyses(projects)
    
    # 创建AI生成日志
    ai_generation_logs = create_ai_generation_logs(projects, versions, test_cases)
    
    print("\n示例数据填充完成！")
    print(f"- 创建了 {len(projects)} 个项目")
    print(f"- 创建了 {len(versions)} 个版本")
    print(f"- 创建了 {len(test_cases)} 个测试用例")
    print(f"- 创建了 {len(ai_templates)} 个AI模板")
    print(f"- 创建了 {len(requirement_analyses)} 个需求分析记录")
    print(f"- 创建了 {len(ai_generation_logs)} 个AI生成日志")

if __name__ == "__main__":
    main()